<template>
	<div>
		<el-dialog :visible.sync="dialogTableVisible" :title="outletName+params.recordDate+'台账'" top="5%" height="70%"
			width="70%" append-to-body @close="resetData">
			<div v-if="dataList" style="background: rgba(74, 148, 241, 0.2);padding: 20px;border-radius: 16px;">
				<div style="margin-bottom: 10px;border-bottom: 1px solid#f5f5f5;">
					<div style="font-size: 16px;font-weight: bold;margin-bottom: 10px;">排口排放情况</div>
				
					<div class="bgfff bra8 pad10 mb10">
						<div class="displayFlex mb10" @click="dialogTableVisible4 = true">
							<div style="width:80px">排放时间：</div>
							<div style="flex:1" class="point">
								<span v-if="outletTotalHour">{{outletTotalHour}}小时</span>
								<span v-else style="color:#3A3EF4">记录排放时间</span>
							</div>
						</div>
				
						<div class="displayFlex mb10">
							<div style="width:80px">污泥产量：</div>
							<el-input v-model="params.mudQty" type="number" style="width:200px" placeholder="污泥产量" />
							<div class="ml10">t</div>
						</div>
				
						<div class="displayFlex mb10">
							<div style="width:80px">处置方式：</div>
							<el-input v-model="params.disposeMethod" style="width:200px" placeholder="处置方式" />
						</div>
				
				
						<!-- <div class="displayFlex">
							<div style="width:80px">耗电量：</div>
							<el-input v-model="params.electricityConsumption" type="number" style="width:200px"
								placeholder="耗电量" />
							<div class="ml10">kwh</div>
						</div> -->
					</div>
				</div>
				<div v-if="dataList.defenceList && dataList.defenceList.length > 0"
					style="margin-bottom: 10px;border-bottom: 1px solid#f5f5f5;">
					<div style="font-size: 16px;font-weight: bold;margin-bottom: 10px;">设施运行情况</div>

					<div class="displayFlexBet bgfff pad10 bra8 mb10">
						<div style="flex:1">设施设备</div>
						<div style="flex:0.5" class="mr10">运行状态</div>
						<div style="flex:1">运行时间</div>

						<div style="flex:2">规格参数</div>
						<div style="flex:1">来源</div>
					</div>
					<div class="bgfff bra8">
						<div class="pad10 font12" v-for="(item,index) in dataList.defenceList"
							style="display:flex;justify-content: space-between;" :key="index" @click="rowClick(item,index)">
							<div style="flex:1">{{item.defenceName}}</div>
							<div style="flex:0.5" v-if="item.isInspect" class="mr10">
								<el-tag v-if="item.resultStr == '不正常'" type="danger" size="mini">{{item.resultStr}}</el-tag>
								<el-tag v-else type="primary" size="mini">{{item.resultStr}}</el-tag>
							</div>
							<div style="flex:0.5" v-else class="mr10">
								<el-select v-model="item.result" placeholder="状态" :disabled="item.dscMn?true:false">
									<el-option label="正常" value="NORMAL" />
									<el-option label="异常" value="ABNORMAL" />
									<el-option label="不生产" value="NOT_PRODUCE" />
								</el-select>
							</div>
							<div style="flex:1" class="point">
								<span v-if="item.totalHour">{{item.totalHour}}小时</span>
								<span v-else style="color:#3A3EF4">记录运行时间</span>
							</div>

							<div style="flex:2;overflow-x: auto;">
								<div v-if="item.valueType == 'STATE'">{{item.resultStr}}</div>
								<div v-else>
									<div v-if="item.parameterList == null && item.dscMn">见DCS图表</div>
									<div v-for="(item1,index1) in item.parameterList" :key="index1"
										:class="[index1== item.parameterList.length-1?'':'mb5']">
										<div style="display: flex;">
											<div style="width: 100px;">{{item1.parameterName}}</div>

											<div style="margin-left: 10px;width:100px">设计值：{{item1.designValueStr}}
											</div>
											<div style="margin-left: 10px;text-align:right">实际值：{{item1.amount}}</div>
										</div>
									</div>
								</div>
							</div>
							<div style="flex:1">{{item.source}}</div>
						</div>
					</div>
				</div>

				<div style="margin-bottom: 10px;border-bottom: 1px solid#f5f5f5;">
					<div class="displayFlex mb10">
						<div style="font-size: 16px;font-weight: bold;">原辅料</div>

						<div style="color: #3A3EF4;" class="font14 ml10 point" @click="getListByOutletId">+ 新增</div>
					</div>

					<el-table :data="dataList.materialList" style="width: 100%;border-radius: 8px;" size="mini" border>
						<el-table-column prop="defenceName" label="设施设备">
						</el-table-column>

						<el-table-column prop="list" label="药剂/辅材">
							<template slot-scope="scope">
								<div v-for="(item1,index1) in scope.row.list" :key="index1"
									:class="[index1==scope.row.list.length-1?'':'mb5']">
									<div style="display: flex;">
										<div style="width: 100px;">{{item1.materialName}}</div>

										<div style="margin-left: 20px;">用量：{{item1.materialQty}}</div>
										<div style="">{{item1.materialUnitValue}}</div>
									</div>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>

			<el-empty v-else description="暂无内容"></el-empty>

			<div slot="footer" class="dialog-footer" v-if="showBottom">
				<el-button @click="dialogTableVisible = false">取 消</el-button>
				<el-button type="primary" @click="createWaterStandingBook">制作台账</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="dialogTableVisible3" top="5%" height="70%" append-to-body title="药剂使用">
			<div>
				<el-form ref="form" label-width="120px">
					<el-form-item label="防治设施">
						<el-select v-model="params1.defenceId" placeholder="请选择防治设施"
							@change="getWaterOutletMaterialListByDefenceId">
							<el-option v-for="(item,index) in dataList1" :label="item.defenceName"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>


					<div v-for="(item,index) in dataList2" :key="index">
						<el-form-item :label="item.materialName">
							<el-input v-model="item.materialQty" placeholder="使用数量" type="number"
								style="width: 90%;"></el-input>
							<span class="ml10">{{item.unitValue}}</span>
						</el-form-item>
					</div>
				</el-form>

				<div class="textCenter">
					<el-button @click="confirmSave" type="primary" style="margin: 0 auto;">+ 保存</el-button>
				</div>

			</div>
		</el-dialog>
		
		<el-dialog :visible.sync="dialogTableVisible4" top="5%" height="70%" :title="'排口排放时间'" append-to-body>
			<div style="display:flex" class="mb10">
				<div>
					<div class="mb10">
						<el-switch v-model="params.outletTimeList[0].isFull" active-text="全天24小时" @change="changeOutetSwitch">
						</el-switch>
					</div>
		
					<div v-if="!params.outletTimeList[0].isFull">
						<div class="displayFlex mb10" v-for="(item2,index2) in params.outletTimeList[0].runtimeList"
							:key="index2">
		
							<el-time-picker v-model="item2.startTime" placeholder="开始时间" value-format="HH:mm:ss"
								format="HH:mm" />
							<span class="ml20 mr20">~</span>
							<el-time-picker v-model="item2.endTime" placeholder="结束时间" value-format="HH:mm:ss"
								format="HH:mm" />
		
							<i class="ml30 el-icon-remove-outline" style="color: #F56C6C;"
								@click="params.outletTimeList[0].runtimeList.splice(index2,1),$forceUpdate()"></i>
						</div>
		
						<div style="color: #3A3EF4;"
							@click="params.outletTimeList[0].runtimeList.push({startTime:'',endTime:''}),$forceUpdate()">
							+添加时段
						</div>
					</div>
				</div>
			</div>
		
			<div class="u-flex pt10 pb10">
				<span class="mr10">所有关联处置设备和排口排放时间同步</span>
				<el-switch v-model="timeIsAll" @change="changeTimeStatus" />
			</div>
		</el-dialog>

		<el-dialog v-if="params.runtimeList[rowIndex]" :visible.sync="dialogTableVisible2" top="5%" height="70%"
			:title="params.runtimeList[rowIndex].defenceName+'的运行时间'" append-to-body>
			<div style="display:flex" class="mb10">
				<div>
					<div class="mb10">
						<el-switch v-model="params.runtimeList[rowIndex].isFull" active-text="全天24小时" @change="changeSwitch">
						</el-switch>
					</div>

					<div v-if="!params.runtimeList[rowIndex].isFull">
						<div class="displayFlex mb10" v-for="(item2,index2) in params.runtimeList[rowIndex].runtimeList"
							:key="index2">

							<el-time-picker v-model="item2.startTime" placeholder="开始时间" value-format="HH:mm:ss"
								format="HH:mm" />
							<span class="ml20 mr20">~</span>
							<el-time-picker v-model="item2.endTime" placeholder="结束时间" value-format="HH:mm:ss"
								format="HH:mm" />

							<i class="ml30 el-icon-remove-outline" style="color: #F56C6C;"
								@click="params.runtimeList[rowIndex].runtimeList.splice(index2,1),$forceUpdate()"></i>
						</div>

						<div style="color: #3A3EF4;"
							@click="params.runtimeList[rowIndex].runtimeList.push({startTime:'',endTime:''}),$forceUpdate()">
							+添加时段
						</div>
					</div>
				</div>
			</div>
			<div class="u-flex pt10 pb10">
				<span class="mr10">所有关联处置设备和排口排放时间同步</span>
				<el-switch v-model="timeIsAll" @change="changeTimeStatus" />
			</div>
		</el-dialog>

	</div>
</template>

<script>
	import moment from 'moment'
	let that
	export default {
		name: 'previewWaterStandingBook',
		props: {
			outletId: {
				type: String,
				default: ''
			},
			outletName: {
				type: String,
				default: ''
			},
			showBottom: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				dialogTableVisible: false,
				dialogTableVisible2: false,
				dialogTableVisible3: false,
				dialogTableVisible4: false,
				params: {
					outletId: '', // 排口id
					recordDate: moment().format('YYYY-MM-DD'), // 日期
					outletTime: '',
					electricityConsumption: '',
					runtimeList: [],
					isFull: false,
					disposeMethod: '',
					mudQty: '',
					outletTimeList: [{
						isFull: false,
						runtimeList: []
					}],
					isOnlineMonitor:false,
				},
				dataList: '',
				rowIndex: 0,
				dataList1: [],
				dataList2: [],
				params1: {
					defenceId: ''
				},
				//imgUrl: "https://www.weifeibangbang.com/wfbb-webupload/service/sys/file/upload/view?appKey=5da5441f62e48aedc7a3853ffc75c2db&prodID=gf&fileID="
			}
		},

		watch: {
			// 监听路由变化
			'params.outletTimeList': {
				handler(n, o) {
					let thisN = JSON.parse(JSON.stringify(n))
					for (let item of thisN) {
						this.outletTotalHour = 0
						for (let item2 of item.runtimeList) {
							if (item2.startTime && item2.endTime) {
								this.outletTotalHour += this.calculateHoursBetweenDates(item2.startTime, item2.endTime)
							}
						}
					}
				},
				deep: true,
			},
			// 监听路由变化
			'params.runtimeList': {
				handler(n, o) {
					let thisN = JSON.parse(JSON.stringify(n))
					for (let item of thisN) {
						item.totalHour = 0
						for (let item2 of item.runtimeList) {
							if (item2.startTime && item2.endTime) {
								item.totalHour += this.calculateHoursBetweenDates(item2.startTime, item2.endTime)
							}
						}
					}
					if (this.dataList && this.dataList.defenceList) {
						let defenceList = JSON.parse(JSON.stringify(this.dataList.defenceList))
						for (let defence of defenceList) {
							let thisIndex = thisN.findIndex(_item => _item.defenceId == defence.defenceId)
							if (thisIndex != -1) defence.totalHour = thisN[thisIndex].totalHour
						}
						this.$set(this.dataList, 'defenceList', defenceList)
						this.$forceUpdate()
					}

				},
				deep: true,
			},
		},

		created: function() {},
		mounted: function() {
			that = this
			that.params.outletId = that.outletId

		},

		methods: {
			resetData() {
				that.params = that.$options.data().params
				that.params.outletId = that.outletId
			},

			changeTimeStatus() {
				this.$confirm('是否确定所有关联处置设备和排口排放时间同步?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let isFlag = false
					if (that.timeIsAll) {
						for (let item of that.params.outletTimeList[0].runtimeList) {
							if (item.startTime && item.endTime) isFlag = true
						}
					}
					if (isFlag == false) {
						that.$nextTick(() => {
							that.timeIsAll = false
						})
						return that.$message.warning("请至少填写一个运行时间！")
					}
			
					for (let item of that.params.runtimeList) {
						item.runtimeList = that.params.outletTimeList[0].runtimeList
					}
					that.$forceUpdate()
				}).catch(() => {
					that.$nextTick(() => {
						that.timeIsAll = false
					})
				});
			
			},
			
			confirmSave() {
				if (!that.params1.defenceId) return that.$message.warning("请选择防治设施！")

				let list = []
				for (let item of that.dataList2) {
					if (item.materialQty) {
						list.push(item)
					}
				}
				if (list.length == 0) return that.$message.warning("请填写使用数量！")

				that.params1.list = list
				that.params1.outletId = that.outletId
				that.params1.outletName = that.outletName
				that.params1.operateTime = that.params.recordDate
				this.$confirm('是否确定保存?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.ajax({
						url: '/waterMaterialChange/saveWaterMaterialChange',
						data: JSON.stringify(that.params1),
						contentType: 'application/json',
						success: function(result) {
							if (result.data) {
								that.$message.success("保存成功！")
								that.dialogTableVisible3 = false
								that.getPreviewWaterStandingBook()
							}
						},
					}, "加载中...")
				})
			},

			getWaterOutletMaterialListByDefenceId() {
				that.ajax({
					url: '/waterOutletDefence/getWaterOutletMaterialListByDefenceId',
					data: {
						defenceId: that.params1.defenceId
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						if (result.data) {
							that.dataList2 = result.data
						}
					},
				}, "加载中...")
			},

			getListByOutletId() {
				that.ajax({
					url: '/waterOutletDefence/getListByOutletId',
					data: {
						outletId: that.outletId
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						if (result.data) {
							that.dataList1 = result.data
							that.dialogTableVisible3 = true
						}
					},
				}, "加载中...")
			},

			changeSwitch() {
				//console.log(that.params.isFull)
				if (that.params.runtimeList[that.rowIndex].isFull) {
					that.params.runtimeList[that.rowIndex].runtimeList = [{
						startTime: "00:00:00",
						endTime: "23:59:59"
					}]
				}
			},
			
			changeOutetSwitch() {
				if (that.params.outletTimeList[0].isFull) {
					that.params.outletTimeList[0].runtimeList = [{
						startTime: "00:00:00",
						endTime: "23:59:59"
					}]
				}
			},

			rowClick(row) {
				let thisIndex = that.dataList.defenceList.findIndex(_item => _item.defenceId == row.defenceId)
				that.rowIndex = thisIndex
				that.dialogTableVisible2 = true
			},


			calculateHoursBetweenDates(date1, date2) {
				if (date1.split(" ").length == 2) date1 = new Date(date1)
				else date1 = new Date(that.params.recordDate + " " + date1)
				if (date2.split(" ").length == 2) date2 = new Date(date2)
				else date2 = new Date(that.params.recordDate + " " + date2)
				const millisecondsPerHour = 1000 * 60 * 60; // 1小时的毫秒数
				const differenceInMilliseconds = Math.abs(date2 - date1); // 两个日期之间的毫秒差
				const hours = Number((differenceInMilliseconds / millisecondsPerHour).toFixed(2));
				return hours;
			},

			createWaterStandingBook() {
				let thisParams = JSON.parse(JSON.stringify(that.params))
				for (let item of thisParams.runtimeList) {
					if (item.runtimeList && item.runtimeList.length > 0) {
						let thisRunTimeList = []
						for (let item2 of item.runtimeList) {
							if (item2.startTime && item2.endTime) {
								if (item2.startTime.includes(that.params.recordDate)) item2.startTime = item2.startTime
								else item2.startTime = that.params.recordDate + " " + item2.startTime

								if (item2.endTime.includes(that.params.recordDate)) item2.endTime = item2.endTime
								else item2.endTime = that.params.recordDate + " " + item2.endTime
								thisRunTimeList.push(item2)
							}
						}
						item.runtimeList = thisRunTimeList
					}
				}
				for (let item of thisParams.outletTimeList) {
					let outletTimeList = []
					if (item.runtimeList && item.runtimeList.length > 0) {
						for (let item2 of item.runtimeList) {
							if (item2.startTime && item2.endTime) {
								if (item2.startTime.includes(that.params.recordDate)) item2.startTime = item2.startTime
								else item2.startTime = that.params.recordDate + " " + item2.startTime
				
								if (item2.endTime.includes(that.params.recordDate)) item2.endTime = item2.endTime
								else item2.endTime = that.params.recordDate + " " + item2.endTime
								outletTimeList.push(item2)
							}
						}
					}
					thisParams.outletTimeList = outletTimeList
				}
				if (this.dataList) thisParams.defenceList = this.dataList.defenceList
				this.$confirm('是否确定制作台账?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.ajax({
						url: '/waterOutlet/createWaterStandingBook',
						data: JSON.stringify(thisParams),
						contentType: 'application/json',
						success: function(result) {
							if (result.data) {
								that.dialogTableVisible = false
								that.$message.success("保存成功！")
								that.params = that.$options.data().params
								that.$emit("success", result.data)
							}
						},
					}, "加载中...")
				})
			},

			open(outletId, recordItem) {
				that.dataList = ''
				that.params.outletId = outletId
				that.params.recordDate = recordItem.date.split(" ")[0]

				that.getPreviewWaterStandingBook()
			},

			getPreviewWaterStandingBook() {
				that.dataList = ''
				that.ajax({
					url: '/waterOutlet/getPreviewWaterStandingBook',
					data: JSON.stringify(that.params),
					contentType: 'application/json',
					success: function(result) {
						if (result.data) {
							that.dataList = result.data
							if (result.data.mudQty) that.params.mudQty = result.data.mudQty
							if (result.data.electricityConsumption) that.params.electricityConsumption =
								result.data.electricityConsumption
							if (result.data.disposeMethod) that.params.disposeMethod = result.data
								.disposeMethod
							if (result.data.runtimeList && result.data.runtimeList.length > 0) {
								that.params.runtimeList = result.data.runtimeList
							} else {
								that.params.runtimeList = []
								for (let item of result.data.defenceList) {
									item.totalHour = 0
									let newItem = {
										defenceId: item.defenceId,
										defenceName: item.defenceName,
										isFull: false,
										runtimeList: []
									}
									that.params.runtimeList.push(newItem)
								}
							}
							
							if (result.data.outletTimeList) that.params.outletTimeList[0].runtimeList = result.data
								.outletTimeList
							that.dialogTableVisible = true
						}
					},
				}, "加载中...")
			},
		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>